package com.crm.utils;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CaptchaUtil {

    private static final int WIDTH = 160;
    private static final int HEIGHT = 60;
    private static final Random random = new Random();

    public static BufferedImage  generateCaptchaImage(HttpServletRequest request) throws IOException {
        // 创建图片
        BufferedImage bufferedImage = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = bufferedImage.createGraphics();

        // 设置背景色
        g2d.setColor(Color.WHITE);
        g2d.fillRect(0, 0, WIDTH, HEIGHT);

        // 生成随机表达式
        String expression = generateRandomExpression();
        int result = calculateExpression(expression);

        // 绘制边框
        g2d.setColor(Color.BLUE);
        g2d.drawRect(0, 0, WIDTH - 1, HEIGHT - 1);

        // 绘制表达式和结果
        Font font = new Font("Arial", Font.BOLD, 24);
        g2d.setFont(font);
        g2d.setColor(Color.BLACK);
        FontMetrics metrics = g2d.getFontMetrics();
        int x = (WIDTH - metrics.stringWidth(expression + " = " + result)) / 2;
        g2d.drawString(expression + " = " + result, x, HEIGHT / 2 + metrics.getAscent() / 2);

        // 添加干扰元素
        addNoise(g2d, WIDTH, HEIGHT);

        // 释放资源
        g2d.dispose();

        // 将验证码文本存入Session
        request.getSession().setAttribute("captchaResult", result);

        return bufferedImage;

    }

    public static String generateCaptcha(HttpServletRequest request) throws IOException {

        BufferedImage captchaImage = generateCaptchaImage(request);

        // 将图片输出为字节流
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(captchaImage, "jpg", baos);
        byte[] imageBytes = baos.toByteArray();

        // 将字节流转换成Base64编码
        String base64Image = Base64.getEncoder().encodeToString(imageBytes);
        return base64Image;
    }

    private static Color getRandomColor() {
        int r = random.nextInt(256);
        int g = random.nextInt(256);
        int b = random.nextInt(256);
        return new Color(r, g, b);
    }

    private static String generateRandomExpression() {
        // 生成两个1到9之间的随机数
        int num1 = random.nextInt(9) + 1;
        int num2 = random.nextInt(9) + 1;

        // 生成随机运算符，确保除法的结果有效
        int operation = random.nextInt(4);
        switch (operation) {
            case 0: // 加法
                return num1 + "+" + num2;
            case 1: // 减法，确保不会产生负数
                if (num1 < num2) {
                    int temp = num1;
                    num1 = num2;
                    num2 = temp;
                }
                return num1 + "-" + num2;
            case 2: // 乘法
                return num1 + "*" + num2;
            case 3: // 除法，确保除数不为0且结果为整数
                while (num2 == 0 || num1 % num2 != 0) {
                    num2 = random.nextInt(9) + 1;
                }
                return num1 + "/" + num2;
            default:
                return "error"; // 理论上不会到达这里
        }
    }

    private static int calculateExpression(String expression) {
        // 使用正则表达式匹配操作符和两边的数字
        Pattern pattern = Pattern.compile("(\\d+)([-+*/])(\\d+)");
        Matcher matcher = pattern.matcher(expression);

        if (!matcher.matches()) {
            throw new IllegalArgumentException("Invalid expression: " + expression);
        }

        int num1 = Integer.parseInt(matcher.group(1));
        int num2 = Integer.parseInt(matcher.group(3));
        char operator = matcher.group(2).charAt(0);

        switch (operator) {
            case '+':
                return num1 + num2;
            case '-':
                return num1 - num2;
            case '*':
                return num1 * num2;
            case '/':
                if (num2 == 0) {
                    throw new IllegalArgumentException("Division by zero in expression: " + expression);
                }
                return num1 / num2;
            default:
                throw new IllegalArgumentException("Invalid operator in expression: " + expression);
        }
    }

    private static void addNoise(Graphics2D g2d, int width, int height) {
        // 添加一些简单的线条作为干扰
        g2d.setColor(Color.GRAY);
        for (int i = 0; i < 20; i++) { // 绘制20条随机线条
            int x1 = random.nextInt(width);
            int y1 = random.nextInt(height);
            int x2 = random.nextInt(width);
            int y2 = random.nextInt(height);
            g2d.drawLine(x1, y1, x2, y2);
        }

        // 添加随机噪点
        g2d.setColor(Color.BLACK);
        for (int i = 0; i < 100; i++) { // 绘制100个随机噪点
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            g2d.fillRect(x, y, 1, 1); // 绘制1x1的矩形作为噪点
        }
    }
}
